﻿Imports System.Text
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.ComponentModel.Composition

<Export(GetType(PluginInterfaces.IClicknLoadPlugin))>
Public Class CnL_xupin
    Implements PluginInterfaces.IClicknLoadPlugin

#Region "Interne Plugin Funktionen"

    Private Function GetResponse(ByVal url As String) As String

        Dim _cookie_container As New CookieContainer
        Dim _http_webrequest As HttpWebRequest
        Dim _http_response As HttpWebResponse
        Dim _rt As String

        If Not url.StartsWith("http://") Then
            url = "http://" & url
        End If

        _http_webrequest = CType(HttpWebRequest.Create(url), HttpWebRequest)
        _http_webrequest.CookieContainer = _cookie_container
        _http_response = CType(_http_webrequest.GetResponse(), HttpWebResponse)

        _rt = New StreamReader(_http_response.GetResponseStream()).ReadToEnd()

        _http_response.Close()

        Return _rt

    End Function

    Private Function GetHostID(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("(www)(\d+).*?(xup)(\.)((?:[a-z][a-z0-9_]*))")
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        For Each m As Match In mc
            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString
                End If
            Next
            mIdx = mIdx + 1
        Next

        Return _rt


    End Function

    Private Function GetvID(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("[a-z0-9]{34}")
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        For Each m As Match In mc
            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString
                End If
            Next
            mIdx = mIdx + 1
        Next

        Return _rt

    End Function

    Private Function GetvTime(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("[0-9]{10}" & Chr(34))
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        For Each m As Match In mc
            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString.Replace(Chr(34), "")
                End If
            Next
            mIdx = mIdx + 1
        Next

        Return _rt

    End Function

    Private Sub ReadWriteStream(readStream As Stream, writeStream As Stream)
        Dim Length As Integer = 256
        Dim buffer As [Byte]() = New [Byte](Length - 1) {}
        Dim bytesRead As Integer = readStream.Read(buffer, 0, Length)
        ' write the required bytes
        While bytesRead > 0
            writeStream.Write(buffer, 0, bytesRead)
            bytesRead = readStream.Read(buffer, 0, Length)
        End While
        readStream.Close()
        writeStream.Close()
    End Sub

#End Region

    Public Function DownloadSFDL(_url As String) As String Implements PluginInterfaces.IClicknLoadPlugin.DownloadSFDL

        Dim _cookie_container As New CookieContainer
        Dim _http_webrequest As HttpWebRequest
        Dim _http_response As HttpWebResponse
        Dim _post As String = String.Empty
        Dim _web_request_url As String = String.Empty
        Dim _byte_array() As Byte
        Dim _dataStream As Stream
        Dim _saveTo As String = String.Empty
        Dim _rt As String = String.Empty
        Dim _tmp_response As String = String.Empty

        Dim _vid As String = String.Empty
        Dim _vtime As String = String.Empty
        Dim _fid As String = String.Empty
        Dim _filename As String = String.Empty
        Dim _host_id As String = String.Empty

        Try

            Debug.WriteLine("RAW Link:" & _url)

            'FID ermitteln

            _fid = _url.Remove(0, _url.IndexOf(","))
            _fid = _fid.Remove(_fid.IndexOf("/"))
            _fid = _fid.Remove(0, 1)
            _fid = _fid.Trim

            Debug.WriteLine("FID=" & _fid)

            'Dateiname ermitteln

            _filename = _url.Remove(_url.Length - 1)
            _filename = _filename.Remove(0, _filename.LastIndexOf("/"))
            _filename = _filename.Remove(0, 1)
            _filename = _filename.Trim

            Debug.WriteLine("Filename=" & _filename)


            _tmp_response = GetResponse(_url)

            _vid = GetvID(_tmp_response)
            _vtime = GetvTime(_tmp_response)
            _host_id = "http://" & GetHostID(_tmp_response)

            Debug.WriteLine("VID=" & _vid)
            Debug.WriteLine("vTIME=" & _vtime)
            Debug.WriteLine("HostID=" & _host_id)

            'Web Request URL zusammenbauen

            _web_request_url = String.Format("{0}/exec/xddl.php?fid={1}&fname={2}&uid=0&key=", _host_id, _fid, _filename)

            Debug.WriteLine("Web Request URL=" & _web_request_url)

            _http_webrequest = CType(HttpWebRequest.Create(_web_request_url), HttpWebRequest)

            _post = String.Format("vid={0}&vtime={1}", _vid, _vtime)

            _byte_array = Encoding.Default.GetBytes(_post)

            With _http_webrequest

                .Method = "POST"
                .CookieContainer = _cookie_container
                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0"
                .ContentType = "application/x-www-form-urlencoded"
                .ContentLength = _byte_array.Length

            End With

            _dataStream = _http_webrequest.GetRequestStream()
            _dataStream.Write(_byte_array, 0, _byte_array.Length)

            _http_response = CType(_http_webrequest.GetResponse(), HttpWebResponse)

            _saveTo = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, IO.Path.GetRandomFileName)

            Dim writeStream As New FileStream(_saveTo, FileMode.Create, FileAccess.Write)

            ' write to the stream
            ReadWriteStream(_http_response.GetResponseStream(), writeStream)

            _http_response.Close()


        Catch ex As Exception
            _rt = ""
        End Try

        _rt = _saveTo

        Return _rt

    End Function

    Public Function SupportedHosts() As List(Of String) Implements PluginInterfaces.IClicknLoadPlugin.SupportedHosts

        Dim _rt_list As New List(Of String)

        _rt_list.Add("xup.in")
        _rt_list.Add("xup.to")

        Return _rt_list

    End Function

    Public Function URLSupported(_url As String) As Boolean Implements PluginInterfaces.IClicknLoadPlugin.URLSupported

        If _url.Contains("xup.in") Or _url.Contains("xup.to") Then
            Return True
        Else
            Return False
        End If

    End Function

    Public Function GetAuthor() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetAuthor
        Return "Seji"
    End Function

    Public Function GetName() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetName
        Return "ClicknLoad Plugin xup.in"
    End Function

    Public Function GetSettingsTab() As Windows.Forms.UserControl Implements PluginInterfaces.ISFDLLoaderPlugin.GetSettingsTab
        Throw New NotImplementedException("Keine Einstellungen vorhanden")
    End Function

    Public Function GetSettingsTabName() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetSettingsTabName
        Throw New NotImplementedException("Keine Einstellungen vorhanden")
    End Function

    Public Function GetVersion() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetVersion
        Return "0.3"
    End Function

    Public Function HasSettings() As Boolean Implements PluginInterfaces.ISFDLLoaderPlugin.HasSettings
        Return False
    End Function

    Public Sub Initialize() Implements PluginInterfaces.ISFDLLoaderPlugin.Initialize
        'Nothing ToDo
    End Sub

    Public Sub SaveSettings() Implements PluginInterfaces.ISFDLLoaderPlugin.SaveSettings
        Throw New NotImplementedException("Keine Einstellungen vorhanden")
    End Sub
End Class
